package servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import beans.Account;
import dao.AccountDAO;

/**
 * Servlet implementation class RegisterServlet
 */
@WebServlet(name = "registerservlet", urlPatterns = { "/registerservlet" })
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public RegisterServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		processRequest(request, response);
	}

	private void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String cmd = request.getParameter("cmd");
		if (cmd != null) {
			String username = request.getParameter("username").trim();
			switch (cmd) {
			case "check":
				Account acc = AccountDAO.selectByUsername(username);
				if (acc != null) {
					response.getWriter().write(true + "");
				} else {
					response.getWriter().write(false + "");
				}
				break;
			case "reg":
				boolean result = AccountDAO.insert(
						username,
						username,
						request.getParameter("password"),
						request.getParameter("sex"),
						request.getParameter("year") + "-"
								+ request.getParameter("month") + "-"
								+ request.getParameter("day"));
				if (!result) {
					response.getWriter()
							.write("Lỗi tạo tài khoản, vui lòng liên hệ Admin để được hỗ trợ");
				} else {
					response.sendRedirect("login");
				}
				break;
			}
		}
	}
}
